package com.example.flinktest.transformation;

import com.example.flinktest.source.Event;
import org.apache.flink.api.java.functions.KeySelector;
import org.apache.flink.streaming.api.datastream.DataStreamSource;
import org.apache.flink.streaming.api.datastream.KeyedStream;
import org.apache.flink.streaming.api.environment.StreamExecutionEnvironment;

public class TransKeyByTest {
    public static void main(String[] args) {
        StreamExecutionEnvironment env = StreamExecutionEnvironment.getExecutionEnvironment();
        env.setParallelism(1);

        DataStreamSource<Event> streamSource = env.fromElements(
                new Event("junsong", "./home", 1000L),
                new Event("Bob", "./cart", 2000L)
        );

        KeyedStream<Event, String> keyedStream = streamSource.keyBy(e -> e.user);
        //使用匿名类实现KeySelector
        KeyedStream<Event, String> keyedStream1 = streamSource.keyBy(
                new KeySelector<Event, String>() {
                    @Override
                    public String getKey(Event event) throws Exception {
                        return event.user;
                    }
                }
        );
        try {
//            keyedStream.max("user").print();
            //按指定字段名称
            streamSource.keyBy(e -> e.user).min("timestamp").print();
            env.execute();
        } catch (Exception e) {
            throw new RuntimeException(e);
        }

    }
}
